import React from "react";
import { Routes, Route, Outlet } from "react-router-dom";
import AuthRouter from "./auth";
import Home from '../components/Home';

// 引入每个目录下面的index.js文件
const ModulesFile = require.context("./", true, /index.js$/);

// 总路由集合
const RouterMap = [];

ModulesFile.keys().reduce((modules, modulePath) => {
    // 路由模块名称   文件夹/index  business/index
    const ModuleName = modulePath.replace(/^.\/(.*)\.js/, "$1")

    //不包含当前index.js 文件
    if (ModuleName !== "index") {
        //路由列表
        const ModuleList = ModulesFile(modulePath)

        //追加到数组
        RouterMap.push(...ModuleList.default)
    }

    return RouterMap
}, {})

const RouterList = () => {
    return (
        <>
            <Routes>
                {/* 默认首页 */}
                <Route path="/" element={<AuthRouter component={<Home />}></AuthRouter>}></Route>

                {/* 把其他路由遍历出来 */}
                <Route path="/" element={<><Outlet /></>}>
                    {
                        RouterMap.map((item, index) => {
                            return (
                                <Route key={index} path={item.path}>
                                    {
                                        item.children && item.children.map((son, idx) => {
                                            return (
                                                <Route key={idx} path={son.path} element={<AuthRouter auth={son.auth} component={<son.component />} />}></Route>
                                            )
                                        })
                                    }
                                </Route>
                            )
                        })
                    }
                </Route>
            </Routes>
        </>
    )
}

export default RouterList